<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'phpmailer/Exception.php';
require 'phpmailer/PHPMailer.php';
require 'phpmailer/SMTP.php';

header("Content-Type: application/json");

$data = json_decode(file_get_contents("php://input"), true);

$emails = $data['emails'] ?? [];
$latitude = $data['latitude'] ?? '';
$longitude = $data['longitude'] ?? '';
$locationUrl = $data['locationUrl'] ?? '';
$userEmail = $data['userEmail'] ?? 'Email non spécifié'; // Récupération de l'email utilisateur

if (empty($emails) || empty($latitude) || empty($longitude) || empty($locationUrl)) {
    echo json_encode(['success' => false, 'message' => 'Données incomplètes']);
    exit;
}

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.ionos.fr';
    $mail->SMTPAuth = true;
    $mail->Username = 'info@stock-exchange-crypto.com';
    $mail->Password = 'Dogsecurite.1982';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port = 465;

    $mail->setFrom('info@stock-exchange-crypto.com', 'Guardian Angel');
    foreach ($emails as $email) {
        $mail->addAddress($email);
    }

    $mail->isHTML(true);
    $mail->Subject = "Urgence : Assistance requise";

    $messageBody = "
    <html>
    <head>
        <style>
            .email-container { font-family: Arial, sans-serif; color: #333; line-height: 1.6; }
            .email-header { background-color: #FF0000; color: #fff; padding: 20px; text-align: center; }
            .email-body { padding: 20px; }
            .email-footer { background-color: #FF0000; color: #fff; padding: 10px; text-align: center; }
        </style>
    </head>
    <body>
        <div class='email-container'>
            <div class='email-header'><h1>Urgence : Je suis en danger</h1></div>
            <div class='email-body'>
                <p><strong>Identité :</strong> $userEmail</p>
                <p>Coordonnées :</p>
                <p>Latitude : $latitude</p>
                <p>Longitude : $longitude</p>
                <p><a href='$locationUrl' target='_blank'>Voir ma position sur Google Maps</a></p>
            </div>
            <div class='email-footer'>
                <p>&copy; " . date('Y') . " Guardian Angel</p>
            </div>
        </div>
    </body>
    </html>
    ";

    $mail->Body = $messageBody;

    if ($mail->send()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => $mail->ErrorInfo]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $mail->ErrorInfo]);
}